package com.itheima.socket;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class SendDemo01 {
    public static void main(String[] args) throws IOException {
        xc();
        js();
//        DatagramSocket ds = new DatagramSocket();
//        Scanner sc = new Scanner(System.in);
//
//        while (true){
//            String s = sc.next();
//            if ("886".equals(s)){
//                break;
//            }
//            byte[] bytes = s.getBytes();
//            DatagramPacket dp = new DatagramPacket(
//                    bytes,bytes.length, InetAddress.getByName("192.168.12.217")
//                    ,8888
//            );
//            ds.send(dp);
//        }
//
//        ds.close();
    }

    public static void xc(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                DatagramSocket ds = null;
                try {
                    ds = new DatagramSocket();
                } catch (SocketException e) {
                    e.printStackTrace();
                }
                Scanner sc = new Scanner(System.in);

                while (true){
                    String s = sc.next();
                    if ("886".equals(s)){
                        break;
                    }
                    byte[] bytes = s.getBytes();
                    DatagramPacket dp = null;
                    try {
                        dp = new DatagramPacket(
                                bytes,bytes.length, InetAddress.getByName("192.168.12.217")
                                ,8888
                        );
                    } catch (UnknownHostException e) {
                        e.printStackTrace();
                    }
                    try {
                        if (ds != null) {
                            ds.send(dp);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                if (ds != null) {
                    ds.close();
                }
            }
        }).start();
    }

    public static void js() throws IOException {
        DatagramSocket ds = new DatagramSocket(8888);
        while (true) {
            byte[] bytes = new byte[1024];
            DatagramPacket dp = new DatagramPacket(bytes,bytes.length);
            ds.receive(dp);
            System.out.println(new String(bytes,0,dp.getLength()));
        }
    }
}
